package com.jiazhong.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiazhong.commons.Mapper.StockMapper;
import com.jiazhong.commons.Util.JsonResult;
import com.jiazhong.commons.Util.ResultTool;
import com.jiazhong.commons.bean.Stock;
import com.jiazhong.commons.config.JwtConfig;
import com.jiazhong.front.service.StockService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements StockService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public JsonResult find(String token) {
        Object userId = JwtConfig.parseJWT(token).get("id");
        HashOperations<String, Object, Object> forHash = stringRedisTemplate.opsForHash();
        ListOperations<String, String> forList = stringRedisTemplate.opsForList();
        Object listKey = forHash.get("GWC_KEY", userId);
        List<String> gwc = forList.range(listKey.toString(), 0, -1);
        String[] bookIds = new String[gwc.size()];
        for (int i = 0; i < gwc.size(); i++) {
            String e = gwc.get(i); // bookId#number
            String bookId = e.substring(0, e.indexOf('#'));
            bookIds[i] = bookId;
        }
        QueryWrapper<Stock> wrapper = new QueryWrapper<>();
        wrapper.in("book_id", bookIds);

        List<Stock> list = list(wrapper);
        return ResultTool.success(list);
    }
}
